// eslint-disable-next-line import/no-extraneous-dependencies
import { Request, Response } from 'express';
import { parse } from 'url';
import { TrainListItem, TrainListParams } from '@/pages/Train/data';

// mock tableListDataSource
const genList = (current: number, pageSize: number) => {
  const trainListDataSource: TrainListItem[] = [];

  for (let i = 0; i < pageSize; i += 1) {
    const index = (current - 1) * pageSize + i;
    trainListDataSource.push({
      id: index + '',
      num: `A1${index}`,
      capacity: Math.floor(Math.random() * 1000),
      line: '一号线',
      manufactureDate: '20230102',
      lastMaintenanceDate: '20240301',
      malfunction: '',
      status: '0'
    });
  }
  // trainListDataSource.reverse();
  return trainListDataSource;
};

// 默认生成100条数据
let trainListDataSource = genList(1, 100);
let total = trainListDataSource.length;

function getTrains(req: Request, res: Response, u: string) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }
  const { current = 1, pageSize = 10 } = req.query;
  const params = (parse(realUrl, true).query as unknown) as TrainListParams;
  // 按条件刷选
  const { num: numc = '', status: statusc } = params;
  let newList: TrainListItem[] = [];
  let condition = false;
  if (numc || statusc) {
    condition = true;
    trainListDataSource.map((item, index) => {
      const { num, status } = item;
      if (numc && statusc && num.includes(numc) && status === statusc) {
        newList.push(item);
      } else if (numc && !statusc && num.includes(numc)) {
        newList.push(item);
      } else if (!numc && statusc && status === statusc) {
        newList.push(item);
      }
    });
  }
  if (condition && newList.length === 0) {
    // 存在条件，但没有满足条件的数据
    const result = {
      data: [],
      total: 0,
      success: true,
      pageSize,
      current: parseInt(`${params.currentPage}`, 10) || 1,
    };
    return res.json(result);
  }
  if (!condition) {
    newList = [...trainListDataSource]
  }
  let dataSource = [...newList].slice(
    ((current as number) - 1) * (pageSize as number),
    (current as number) * (pageSize as number),
  );
  const sorter = JSON.parse(params.sorter as any);
  if (sorter) {
    dataSource = dataSource.sort((prev, next) => {
      let sortNumber = 0;
      Object.keys(sorter).forEach((key) => {
        if (sorter[key] === 'descend') {
          if (prev[key] - next[key] > 0) {
            sortNumber += -1;
          } else {
            sortNumber += 1;
          }
          return;
        }
        if (prev[key] - next[key] > 0) {
          sortNumber += 1;
        } else {
          sortNumber += -1;
        }
      });
      return sortNumber;
    });
  }
  if (params.filter) {
    const filter = JSON.parse(params.filter as any) as {
      [key: string]: string[];
    };
    if (Object.keys(filter).length > 0) {
      dataSource = dataSource.filter((item) => {
        return Object.keys(filter).some((key) => {
          if (!filter[key]) {
            return true;
          }
          if (filter[key].includes(`${item[key]}`)) {
            return true;
          }
          return false;
        });
      });
    }
  }
  const result = {
    data: dataSource,
    total: trainListDataSource.length,
    success: true,
    pageSize,
    current: parseInt(`${params.currentPage}`, 10) || 1,
  };

  return res.json(result);
}

function postTrain(req: Request, res: Response, u: string, b: Request) {
  let realUrl = u;
  if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
    realUrl = req.url;
  }

  const body = (b && b.body) || req.body;
  console.info(body);
  const { method, id, ...rest } = body;

  switch (method) {
    /* eslint no-case-declarations:0 */
    case 'delete':
      trainListDataSource = trainListDataSource.filter((item) => id.indexOf(item.id) === -1);
      break;
    case 'post':
      (() => {
        const { num, capacity, line, manufactureDate } = body;
        const newTrain: TrainListItem = {
          id: trainListDataSource.length + '',
          num,
          capacity,
          line,
          manufactureDate,
          lastMaintenanceDate: '',
          status: '0',
          malfunction: ''
        };
        trainListDataSource.unshift(newTrain);
        return res.json(newTrain);
      })();
      return;
    case 'update':
      (() => {
        const { num, capacity, line, manufactureDat, lastMaintenanceDate, status, malfunction } = body;
        let newTrain = {};
        trainListDataSource = trainListDataSource.map((item) => {
          if (item.id === id) {
            newTrain = { id, ...rest };
            return { ...item, num, capacity, line, manufactureDat, lastMaintenanceDate, status, malfunction };
          }
          return item;
        });
        return res.json(newTrain);
      })();
      return;
    default:
      break;
  }

  const result = {
    list: trainListDataSource,
    pagination: {
      total: trainListDataSource.length,
    },
  };

  res.json(result);
}

export default {
  'GET /api/train': getTrains,
  'POST /api/train': postTrain,
};
